package com.yhq.basic.thread.juc;

import java.util.concurrent.Phaser;

/**
 * @author hqyin
 * @date 2025/5/13 5:11 PM
 */
public class TestPhaser {
    public static void main(String[] args) {
        Phaser phaser = new Phaser() {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                switch (phase) {
                    case 0:
                        System.out.println("当前状态："+phase+",当前任务数："+registeredParties);
                        break;
                    case 1:
                        System.out.println("当前状态："+phase+",当前任务数："+registeredParties);
                        break;
                    case 2:
                        System.out.println("当前状态："+phase+",当前任务数："+registeredParties);
                        break;
                }
                return registeredParties==1;
            }
        };

//        phaser.register();

        for (int i = 0; i < 2; i++) {
            phaser.register();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+":吃早饭");
                    phaser.arriveAndAwaitAdvance();

                    System.out.println(Thread.currentThread().getName()+":吃中饭");
                    phaser.arriveAndAwaitAdvance();

                    System.out.println(Thread.currentThread().getName()+":吃晚饭");
                    phaser.arriveAndAwaitAdvance();

                    phaser.arriveAndDeregister();
                }
            },"线程"+i).start();
        }

        while (!phaser.isTerminated()) {
            int phase = phaser.arriveAndAwaitAdvance();
            if(phase ==1) {
                for (int i = 0; i <3; i++) {
                    phaser.register();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            System.out.println(Thread.currentThread().getName()+":吃中饭");
                            phaser.arriveAndAwaitAdvance();

                            phaser.arriveAndDeregister();
                        }
                    },"线程"+i).start();
                }
                break;
            }

        }


    }
}
